import Vue from 'vue'
import router from '@/router'

const axios_ = require('axios')

const axios = axios_.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 10000,
});


axios.interceptors.request.use(function (config) {
  //如果token存在，那么将token存入到请求头中
  let token = sessionStorage.getItem("token")
  if (token != null) {
    config.headers['Authorization'] = token
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  Vue.prototype.$toast("请求失败")

  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {


  console.log(response.data)
  return response.data
}, function (error) {
  Vue.prototype.$toast("响应失败")
  //如果code是522，说明未登录或者token过期，需要重新登陆
  if (error.response.status == 522) {
    sessionStorage.removeItem("token")

    router.push({ name: 'login' })
  }

  return Promise.reject(error);
})

export default axios